<template>
  <div>
    <div class="toolbar">
      <el-form :inline="true" :model="q" size="mini">
        <el-form-item>
          <el-button type="text" disabled>{{this.Timetype?'创建时间':'到账时间'}}
          </el-button>
          (
          <el-button type="text" @click="toggleTimetype">点击切换</el-button>
          )
          <el-date-picker v-if="Timetype" v-model="q.created_at_begin" :picker-options="regStart_options"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间"></el-date-picker>
          <el-date-picker v-else v-model="q.success_at_begin" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                          placeholder="选择日期时间"></el-date-picker>
          -
          <el-date-picker v-if="Timetype" v-model="q.created_at_end" :picker-options="regEnd_options"
                          value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间"></el-date-picker>
          <el-date-picker v-else v-model="q.success_at_end" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                          placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="订单ID:">
          <el-input v-model="q.order_id" placeholder="订单ID" prefix-icon="el-icon-edit"></el-input>
        </el-form-item>
        <el-form-item label="商户订单ID:">
          <el-input v-model="q.mch_recharge_id" placeholder="商户订单ID" prefix-icon="el-icon-edit"></el-input>
        </el-form-item>
        <el-form-item label="所属商户:">
          <el-select v-model="q.mch_id" clearable placeholder="请选择">
            <el-option
              v-for="item in MerchantsList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单类型:">
          <el-select v-model="q.source" clearable placeholder="请选择">
            <el-option
              v-for="item in orderType"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款账号ID:">
          <el-input v-model="q.receipt_address_id" placeholder="收款账号" prefix-icon="el-icon-edit"></el-input>
        </el-form-item>
        <el-form-item label="所属总代:">
          <el-select v-model="q.parent_id" clearable filterable placeholder="请输入所属总代">
            <el-option v-for="item of AgencyMainList" :key="item.id" :label="item.id+'>'+item.user_name+'>'+item.nickname"
              :value="item.id" ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="代理账号:">
          <el-select v-model="q.agency_id" clearable filterable placeholder="请输入代理账号">
            <el-option v-for="item of AgencyList" :key="item.id" :label="item.id+'>'+item.user_name+'>'+item.nickname"
              :value="item.id" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID:">
          <el-input v-model="q.user_id" placeholder="用户ID" prefix-icon="el-icon-edit"></el-input>
        </el-form-item>

        <el-form-item label="支付方式:">
          <el-select v-model="q.pay_type" clearable placeholder="请选择">
            <el-option v-for="(item,index) in this.$store.state.app.payType"
              :key="index" :label="item" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态:">
          <el-select clearable v-model="q.status" placeholder="请选择">
            <el-option v-for="(item,index) in orderStatus" :key="item" :label="item"
                       :value="index" v-if="index!=10"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button type="danger" @click="reload">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div>
      <el-button size="mini" @click="downloadData" :type="downloading?'info':'primary'" :loading="downloading" icon="el-icon-printer" style="float: right">{{downloading?'导出中...':'导出报表'}}</el-button>
    </div>

    <el-table v-if="listData.items" :data="listData.items" v-loading.body="listLoading" @sort-change="sortlist" size="mini"  :height="listData.total>25?'65vh':null" stripe border fit
              highlight-current-row>
      <el-table-column prop="id" label='订单ID' width="80"></el-table-column>
      <el-table-column prop="mch_recharge_id" label='商户订单ID' width="220"></el-table-column>
      <el-table-column prop="mch_name" label='所属商户' width="160"></el-table-column>
      <el-table-column prop="user_id" label='用户ID' width="140"></el-table-column>
      <el-table-column prop="agency_name" label='代理账号' width="140"></el-table-column>
      <el-table-column prop="agency.parent.nickname" label='所属总代' width="140"></el-table-column>
      <el-table-column prop="source" label='订单类型' width="100" :formatter="FormartToText"></el-table-column>
      <el-table-column prop="pay_type" label='支付方式' width="100" :formatter="FormartToText">
        <template slot-scope="scope">{{$store.state.app.payType[scope.row.pay_type]}}</template>
      </el-table-column>
      <el-table-column prop="receipt_address_id" label='收款账号ID' width="120"></el-table-column>
      <el-table-column prop="amount" label='订单金额' width="100"></el-table-column>
      <el-table-column prop="real_amount" label='充值金额' width="100"></el-table-column>
      <el-table-column prop="recharge_amount" label='到账金额' width="100"></el-table-column>
      <el-table-column prop="chased_amount" label='追分金额' width="100"></el-table-column>
      <el-table-column prop="status" label='订单状态' width="170" :formatter="FormartToText"></el-table-column>
      <el-table-column prop="remark" label='备注' width="250"></el-table-column>

      <el-table-column prop="created_at" label='创建时间' width="180"></el-table-column>
      <el-table-column prop="success_at" label='到账时间' width="180"></el-table-column>
      <el-table-column prop="updated_at" label='最后更新时间' width="180"></el-table-column>

      <!--      <el-table-column prop="status" label='订单状态' width="300">-->
      <!--        <template slot-scope="scope">{{$store.state.app.orderStatus[Number(scope.row.status)]}}</template>-->
      <!--      </el-table-column>-->

      <!--      <el-table-column label="操作" width="80" fixed="right">-->
      <!--        <template slot-scope="scope">-->
      <!--          <div>-->
      <!--            <el-button v-if="Number(scope.row.status)===3" type="primary" size="mini" @click="addScoreShow(scope.row)">-->
      <!--              追分-->
      <!--            </el-button>-->
      <!--          </div>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="q.page_no" :page-sizes="$store.state.app.pageSizeArr"
                     :page-size="q.page_size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="listData.total">
      </el-pagination>
    </div>
    <add-score v-if="showAddScore" :showUpdate.sync="showAddScore" :id="show_id"
               :MerchantsList="MerchantsList"></add-score>
  </div>


</template>

<script>
  import {getOrders, getMerchantsList, exportExel,getAgencyList} from '@/api'
  import AddScore from './AddScore.vue'
  import {queryFilter} from '@/utils/patch'
  // import { downloadDataToFile } from "@/utils/CommonJs";

  export default {
    components: {AddScore},
    data() {
      return {
        listData: {},
        // q: {page_size: 30, page_no: 1, agency_type: 2},
        q: {page_size: 30, page_no: 1},
        listLoading: false,
        showUpdate: false,
        settleCycle: this.$store.state.app.settleCycle,
        show_id: null,
        MerchantsList: [],
        AgencyType: this.$store.state.app.AgencyType,
        isEnable: false,
        isShow: false,
        searchTime: [],
        Timetype: false,
        score: 0,
        orderStatus: this.$store.state.app.orderStatus,
        showAddScore: false,
        regStart_options: this.startDate_reg(),
        regEnd_options: this.endDate_reg(),
        orderType: [
          {id: 1, text: '手动充值'},
          {id: 2, text: '自动充值'}
        ],
        payType: [
          {id: 1, text: '支付宝'},
          {id: 2, text: '微信'},
          {id: 3, text: '银行卡'},
          {id: 4, text: '花呗'},
          {id: 5, text: '信用卡支付宝'},
          {id: 6, text: '微信卡微信'},
          {id: 7, text: '支付宝自助'},
          {id: 8, text: '微信自助'},
          {id: 9, text: '银行卡自助'},
        ],
      AgencyMainList: [],
      AgencyList: [],
        downloading: false
        // parentObj:[]
      }
    },
    activated() {
      this.getList()
      this.getMerchantsList()
    this.getAgencyList()
    this.getChildAgencyList()
    },
    deactivated() {
      this.listLoading = false
    },
    methods: {
      downloadData() {
        this.downloading = true
        getOrders(Object.assign({},this.q, {export: 1 })).then(res => {
          if (res.status === 0) {
            this.exportExel(res.data.task_id)
            // this.downloading = false
            // const tHeader = ['订单ID', '商户订单ID', '所属商户', '用户ID', '代理账号', '所属总代', '订单类型', '支付方式', '收款账号ID', '订单金额', '充值金额', '到账金额', '追分金额', '订单状态', '备注', '创建时间', '到账时间', '最后更新时间'];
            // const filterVal = ['id', 'mch_recharge_id', 'mch_name', 'user_id', 'agency_name', 'agency.parent.nickname', 'source', 'pay_type', 'receipt_address_id', 'amount:int', 'real_amount:int', 'recharge_amount:int', 'chased_amount:int', 'status', 'remark', 'created_at', 'success_at', 'updated_at'];
            // downloadDataToFile(res,tHeader,filterVal,`用户订单管理${timedate.dateTodayHMS}`)
          }
        })
      },
    async exportExel (task_id) {
      const exportStatusRes = await exportExel(task_id)
      if (exportStatusRes.status === 0) {
        switch (exportStatusRes.data.status) {
          case 0:
            setTimeout(() => {
              this.exportExel(task_id)
            }, 1500)
            break
          case 1:
            window.location.href = `${window.location.origin}/export_data/${exportStatusRes.data.file_name}`
            this.downloading = false
            this.$message.success('导出成功')
            break;
          case 2:
              this.$message.info('导出失败')
              this.downloading = false
            break;
          case 3:
              this.$message.info('取消导出')
              this.downloading = false
            break;
        }
      }
    },
      toggleTimetype() {
        if (this.Timetype) {
          delete this.q.created_at_begin
          delete this.q.created_at_end
          this.Timetype = !this.Timetype
        } else {
          delete this.q.success_at_begin
          delete this.q.success_at_end
          this.Timetype = !this.Timetype
        }
      },
      query() {
        this.q = Object.assign(this.q, {page_no: 1, page_size: 30})
        this.getList()
      },
      reload() {
        this.q = {page_size: 30, page_no: 1}
        this.getList()
      },
      sortlist(sort) {
        this.q.$orderby = sort.prop
        this.getList()
      },
      handleSizeChange(val) {
        this.q.page_size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.q.page_no = val
        document.documentElement.scrollTop = 0
        document.body.scrollTop = 0
        this.getList()
      },
    getAgencyList () {
      getAgencyList({ agency_type: 2, page_size: 1000 }).then(res => {
        if (res.status === 0) {
          this.AgencyMainList = res.data.items
        }
      })
    },
    getChildAgencyList () {
      getAgencyList({ agency_type: 1, page_size: 1000 }).then(res => {
        if (res.status === 0) {
          this.AgencyList = res.data.items
        }
      })
    },
      getList() {
        queryFilter(this.q)
        getOrders(this.q).then(res => {
          if (res.status === 0) {

            this.listData = {}
            this.listLoading = false
            this.listData = res.data
            this.listData.items = Array.from(res.data.items, x => Object.assign({}, x, {
              amount: Number(x.amount) / 100,
              real_amount: Number(x.real_amount) / 100,
              recharge_amount: Number(x.recharge_amount) / 100,
              chased_amount: Number(x.chased_amount) / 100
            }))
          }
        })
      },
      getMerchantsList() {
        getMerchantsList().then(res => {
          if (res.status === 0) {
            this.MerchantsList = res.data.items
          }
        })
      },
      addScoreShow(seleRow) {
        this.show_id = seleRow.id
        this.showAddScore = true
      },
      startDate_reg() {
        let self = this;
        return {
          disabledDate(time) {
            if (self.q.created_at_end) {
              return new Date(self.q.created_at_end).getTime() < time.getTime();
            } else {
              return false;
            }
          }
        };
      },
      endDate_reg() {
        let self = this;
        return {
          disabledDate(time) {
            if (self.q.created_at_begin) {
              return (
                new Date(self.q.created_at_begin).getTime() > time.getTime()
              );
            } else {
              return false;
            }
          }
        };
      },
      FormartToText(row, column) {
        switch (column.property) {

          case 'pay_method':
            return this.$store.state.app.PayMethodType[row.pay_method]

          case 'pay_type':
            return this.$store.state.app.payType[row.pay_type]

          case 'source':
            return this.$store.state.app.orderType[row.source]

          case 'status':
            return this.$store.state.app.orderStatus[row.status]


        }
      }
    },
    watch: {
      showUpdate() {
        if (!this.showUpdate) {
          this.getList()
        }
      }
    }
  }
</script>
